import React, {Component} from 'react'
import PubSub from "pubsub-js";
import './index.scss'

export default class Footer extends Component {
    handleCheckAll = (event) => {
        PubSub.publish('updateAllTodoDone', event.target.checked)
    }
    handleClearAllDone = () => {
        PubSub.publish('clearAllDone')
    }
    state = {
            "total":0,
            "doneCount":0
    }
    componentDidMount() {
        console.log("Footer:componentDidMount")
        this.token = PubSub.subscribe('todo_data', (_, data) => {
            const state = this.state
            const {todos} = data
            state.total =  todos.length
            state.doneCount = todos.reduce((pre, current) => pre + current.done, 0)
            this.setState(state)
        })
    }

    componentWillUnmount() {
        console.log("Footer:componentWillUnmount")
        PubSub.unsubscribe(this.token)
    }

    render() {
        const {total,doneCount} = this.state
        return (
            <div className='todo-footer'>
                <label>
                    <input type='checkbox' onChange={this.handleCheckAll}
                           checked={(doneCount > 0 && doneCount === total)}/>
                </label>
                <span>已完成{doneCount}</span> /全部{total}
                <button onClick={this.handleClearAllDone} className='btn btn-danger'>清楚已完成任务</button>
            </div>
        )
    }
}
